/*
 * Copyright (c) 2015 Uwantsoft Ltd.
 * www.uwantsoft.com
 * All rights reserved.
 * This software is the confidential and proprietary information of
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Uwantsoft.
 */

package com.uwantsoft.business.facade;

import com.uwantsoft.business.facade.dto.city.CityDetailDto;
import com.uwantsoft.business.facade.dto.city.CityDto;
import com.uwantsoft.business.facade.dto.city.CityFormDto;
import com.uwantsoft.business.facade.dto.city.CityOverViewDto;
import com.uwantsoft.business.facade.dto.parking.CityOverviewQueryCondition;
import com.uwantsoft.business.service.CityServiceImpl;
import com.uwantsoft.business.service.domain.city.City;
import com.uwantsoft.util.paging.DefaultPaginatedList;
import com.uwantsoft.util.paging.PagingListLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Leipeichen.
 */
@Component(value = "cityFacade")
public class CityFacadeImpl {

    @Resource(name = "cityService")
    private CityServiceImpl cityService;

    public List<CityDto> obtainCities() {
       List<CityDto> cityDtoList = new ArrayList<CityDto>();
       List<City> cityList = cityService.findCities();
       for (City city : cityList){
           cityDtoList.add(city.convert());
       }
       return cityDtoList;
    }

    public DefaultPaginatedList obtainCities(final CityOverviewQueryCondition condition) {
        return new DefaultPaginatedList(condition).loadData(new PagingListLoader() {
            @Override
            public List loadList() {
                List<CityOverViewDto> cityOverViewDtoList = new ArrayList<CityOverViewDto>();
                List<City> cityList = cityService.findCities(condition);
                for (City city : cityList){
                    cityOverViewDtoList.add(city.convertOverView());
                }
                return cityOverViewDtoList;
            }

            @Override
            public int loadFullListSize() {
                return cityService.findCityTotalNumber(condition);
            }
       });
    }

    public void addOrUpdate(CityFormDto cityFormDto) {
        City city = cityService.findCity(cityFormDto.getGuid());
        if(city == null){
            city = City.create(cityFormDto);
            cityService.add(city);
        }else{
            city.update(cityFormDto);
        }
    }

    public CityFormDto obtainCity(String guid) {
        City city = cityService.findCity(guid);
        if(city != null){
            return city.convertCityForm();
        }
        return new CityFormDto();
    }

    public CityDetailDto obtainCityDetail(String guid) {
        City city = cityService.findCity(guid);
        if(city != null){
            return city.convertDetail();
        }
        return new CityDetailDto();
    }
}
